package com.hsy.sunflowerbao.home.ui

import android.support.design.widget.TabLayout
import android.support.v4.util.SparseArrayCompat
import android.support.v7.app.AlertDialog
import android.text.InputFilter
import android.text.InputType
import android.view.View

import com.flux.action.RxStoreChange
import com.flux.utils.GsonUtil
import com.hsy.sunflowerbao.R
import com.hsy.sunflowerbao.base.action.ActionType
import com.hsy.sunflowerbao.base.ui.fragment.BaseFragment
import com.hsy.sunflowerbao.base.ui.widget.FragmentAdapter
import com.hsy.sunflowerbao.common.ui.MainActivity
import com.hsy.sunflowerbao.home.action.HomeActionCreator
import com.hsy.sunflowerbao.home.store.HomeStore
import com.hsy.sunflowerbao.login.ui.LoginActivity
import com.hsy.sunflowerbao.utils.CommonUtils

import kotlinx.android.synthetic.main.dialog_confirm.*
import kotlinx.android.synthetic.main.dialog_input.*
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.layout_tab_fixed.*

/**
 * 首页Fragment
 * Created on 2018/3/26.
 *
 * @author yang
 */
class HomeFragment : BaseFragment<HomeStore>(), View.OnClickListener {

    /**
     * 数据缓存器
     */
    override var store = HomeStore(dispatcher)
    /**
     * 事件产生器
     */
    private val creator = HomeActionCreator(dispatcher, manager)
    /**
     * 布局文件
     */
    override val fragmentLayout: Int
        get() = R.layout.fragment_home

    /**
     * fragment列表
     */
    private val fragments = SparseArrayCompat<ListFragment>()

    override fun initView(view: View?) {
        exit.setOnClickListener(this)
        homeScan.setOnClickListener(this)
        homeSearch.setOnClickListener(this)
        homeTitle.text = CommonUtils.getShopName()
        initFragments()
    }

    override fun onRxStoreChanged(change: RxStoreChange) {
        if (change.storeId == store.tag && change.type == ActionType.GET_SEARCH_USER) {
            CommonUtils.hideProgressDialog()
            if (change.success) {
                startActivity(DetailActivity::class.java, GsonUtil.toJson(store.user))
            }
        }
    }

    /**
     * 初始化fragments
     */
    private fun initFragments() {
        val fragment0 = ListFragment.getInstance("0")
        fragments.put(0, fragment0)
        val fragment1 = ListFragment.getInstance("1")
        fragments.put(1, fragment1)
        val fragment2 = ListFragment.getInstance("2")
        fragments.put(2, fragment2)

        viewPager.adapter = FragmentAdapter(childFragmentManager, fragments, arrayOf("全部", "历史消券", "历史积分"))
        val listener = TabListener()
        tabs.setupWithViewPager(viewPager)
        tabs.addOnTabSelectedListener(listener)
        listener.onTabSelected(tabs.getTabAt(0))
    }

    /**
     * 点击事件
     */
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.exit -> {
                val dialog = context?.let {
                    AlertDialog.Builder(it)
                            .setView(R.layout.dialog_confirm)
                            .setCancelable(true)
                            .show()
                }
                dialog?.setCanceledOnTouchOutside(true)
                dialog?.dialog_msg?.text = "您确认要退出吗？"
                dialog?.dialog_cancel?.setOnClickListener { dialog.cancel() }
                dialog?.dialog_confirm?.setOnClickListener {
                    dialog.dismiss()
                    CommonUtils.clearToken()
                    startActivityWithTaskCleared(LoginActivity::class.java)
                }
            }
            R.id.homeScan -> (attachedActivity as MainActivity).startScan()
            R.id.homeSearch -> {
                val dialog = AlertDialog.Builder(context!!)
                        .setView(R.layout.dialog_input)
                        .setCancelable(true)
                        .show()
                dialog.setCanceledOnTouchOutside(true)
                dialog.dialog_input.hint = getString(R.string.hint_home_phone)
                dialog.dialog_input.filters = arrayOf(InputFilter.LengthFilter(11))
                dialog.dialog_input.inputType = InputType.TYPE_CLASS_PHONE
                dialog.dialog_input_cancel.setOnClickListener { dialog.cancel() }
                dialog.dialog_input_confirm.setOnClickListener {
                    val name = dialog.dialog_input.text.toString()
                    if (name.isNotEmpty()) {
                        dialog.cancel()
                        CommonUtils.showProgressDialog(context)
                        creator.searchUser(name)
                    } else {
                        showToast(R.string.msg_home_phone)
                    }
                }
            }
        }
    }

    /**
     * 页面切换监听
     */
    private inner class TabListener : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {
            viewPager.setCurrentItem(tab!!.position, false)
        }

        override fun onTabUnselected(tab: TabLayout.Tab) {}
        override fun onTabReselected(tab: TabLayout.Tab) {}
    }
}